/**
 * @Date: 2022-03-07 13:06:21
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-14 09:19:27
 * @FilePath: \zhihuReal\app.js
 * @Description: app
 */
// @ts-nocheck
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const koabody = require('koa-body')
const logger = require('koa-logger')
const routing = require('./routes/ddd.js')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const mongoose = require('./db/db')
const path = require('path')
const koaStatic = require('koa-static')
//路由
const home = require('./routes/home')
const users = require('./routes/users')
const topic = require('./routes/topic')
const question = require('./routes/question')
const answer = require('./routes/answer')
const comment = require('./routes/comment')
// error handler
// onerror(app)
app.use(koaStatic(path.join(__dirname, 'public')))
app.use(error({
  //去除stack
  postFormat: (e, {
    stack,
    ...rest
  }) => process.env.NODE_ENV === 'production' || 'development' ? rest : {
    stack,
    ...rest
  }
}))
// middlewares
app.use(koabody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, '/public/uploads'),
    keepExtensions: true
  }
}))

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))
app.use(parameter(app))
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
// routing(app)
app.use(home.routes()).use(home.allowedMethods())
app.use(users.routes()).use(users.allowedMethods())
app.use(topic.routes()).use(topic.allowedMethods())
app.use(question.routes()).use(question.allowedMethods())
app.use(answer.routes()).use(answer.allowedMethods())
app.use(comment.routes()).use(comment.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app